<template>
  <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
    <el-form-item label="客户名称" prop="name">
      <el-input v-model="form.name" />
    </el-form-item>

    <el-form-item label="客户阶段" prop="stage">
      <el-select v-model="form.stage" placeholder="请选择客户阶段">
        <el-option
          v-for="stage in customerStages"
          :key="stage.value"
          :label="stage.label"
          :value="stage.value"
        />
      </el-select>
    </el-form-item>

    <el-form-item label="客户来源" prop="source">
      <el-select v-model="form.source" placeholder="请选择客户来源">
        <el-option
          v-for="source in customerSources"
          :key="source.value"
          :label="source.label"
          :value="source.value"
        />
      </el-select>
    </el-form-item>

    <el-form-item label="所属部门" prop="departments">
      <el-select
        v-model="form.departments"
        multiple
        placeholder="请选择部门"
        @change="handleDepartmentChange"
      >
        <el-option
          v-for="dept in departments"
          :key="dept.id"
          :label="dept.name"
          :value="dept.id"
        />
      </el-select>
    </el-form-item>

    <el-form-item label="销售" prop="sales">
      <el-select
        v-model="form.sales"
        placeholder="请选择销售"
        :disabled="!form.departments.length"
      >
        <el-option
          v-for="user in departmentUsers"
          :key="user.id"
          :label="user.name"
          :value="user.id"
        />
      </el-select>
    </el-form-item>

    <el-form-item label="客服" prop="service">
      <el-select v-model="form.service" placeholder="请选择客服">
        <el-option
          v-for="user in serviceUsers"
          :key="user.id"
          :label="user.name"
          :value="user.id"
        />
      </el-select>
    </el-form-item>

    <el-form-item label="所属行业" prop="industries">
      <el-select v-model="form.industries" multiple placeholder="请选择行业">
        <el-option
          v-for="industry in industries"
          :key="industry.id"
          :label="industry.name"
          :value="industry.id"
        />
      </el-select>
    </el-form-item>

    <el-form-item label="拜访地址" prop="visitAddress">
      <el-input v-model="form.visitAddress" />
    </el-form-item>

    <el-form-item label="注册地址" prop="registerAddress">
      <el-input v-model="form.registerAddress" />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm">保存</el-button>
      <el-button @click="resetForm">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import type { Customer, Department, User, Industry } from '@/types'

const props = defineProps<{
  customer?: Customer
}>()

const emit = defineEmits<{
  (e: 'submit', customer: Customer): void
  (e: 'cancel'): void
}>()

const formRef = ref<FormInstance>()
const form = ref({
  name: '',
  stage: '',
  source: '',
  departments: [] as number[],
  sales: null as number | null,
  service: null as number | null,
  industries: [] as number[],
  visitAddress: '',
  registerAddress: ''
})

const departments = ref<Department[]>([])
const departmentUsers = ref<User[]>([])
const serviceUsers = ref<User[]>([])
const industries = ref<Industry[]>([])

const customerStages = [
  { value: 'LEAD', label: '潜在客户' },
  { value: 'OPPORTUNITY', label: '意向客户' },
  { value: 'CUSTOMER', label: '成交客户' }
]

const customerSources = [
  { value: 'REFERRAL', label: '转介绍' },
  { value: 'WEBSITE', label: '官网' },
  { value: 'OTHER', label: '其他' }
]

const rules: FormRules = {
  name: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
  stage: [{ required: true, message: '请选择客户阶段', trigger: 'change' }],
  source: [{ required: true, message: '请选择客户来源', trigger: 'change' }],
  departments: [{ required: true, message: '请选择所属部门', trigger: 'change' }],
  sales: [{ required: true, message: '请选择销售', trigger: 'change' }],
  service: [{ required: true, message: '请选择客服', trigger: 'change' }],
  industries: [{ required: true, message: '请选择所属行业', trigger: 'change' }]
}

const fetchDepartments = async () => {
  try {
    const response = await axios.get('/api/departments')
    departments.value = response.data
  } catch (error) {
    console.error('获取部门列表失败:', error)
    ElMessage.error('获取部门列表失败')
  }
}

const fetchDepartmentUsers = async (departmentIds: number[]) => {
  try {
    const response = await axios.get('/api/departments/users', {
      params: { departmentIds: departmentIds.join(',') }
    })
    departmentUsers.value = response.data
  } catch (error) {
    console.error('获取部门用户失败:', error)
    ElMessage.error('获取部门用户失败')
  }
}

const fetchServiceUsers = async () => {
  try {
    const response = await axios.get('/api/users/service')
    serviceUsers.value = response.data
  } catch (error) {
    console.error('获取客服列表失败:', error)
    ElMessage.error('获取客服列表失败')
  }
}

const fetchIndustries = async () => {
  try {
    const response = await axios.get('/api/industries')
    industries.value = response.data
  } catch (error) {
    console.error('获取行业列表失败:', error)
    ElMessage.error('获取行业列表失败')
  }
}

const handleDepartmentChange = async (departmentIds: number[]) => {
  form.value.sales = null
  if (departmentIds.length > 0) {
    await fetchDepartmentUsers(departmentIds)
  } else {
    departmentUsers.value = []
  }
}

const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      const customerData = {
        ...form.value,
        departments: departments.value.filter(dept => form.value.departments.includes(dept.id)),
        sales: departmentUsers.value.find(user => user.id === form.value.sales),
        service: serviceUsers.value.find(user => user.id === form.value.service),
        industries: industries.value.filter(industry => form.value.industries.includes(industry.id))
      }
      emit('submit', customerData)
    }
  })
}

const resetForm = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
}

onMounted(async () => {
  await Promise.all([
    fetchDepartments(),
    fetchServiceUsers(),
    fetchIndustries()
  ])

  if (props.customer) {
    form.value = {
      name: props.customer.name,
      stage: props.customer.stage,
      source: props.customer.source,
      departments: props.customer.departments.map(dept => dept.id),
      sales: props.customer.sales?.id || null,
      service: props.customer.service?.id || null,
      industries: props.customer.industries.map(industry => industry.id),
      visitAddress: props.customer.visitAddress || '',
      registerAddress: props.customer.registerAddress || ''
    }
    if (form.value.departments.length > 0) {
      await fetchDepartmentUsers(form.value.departments)
    }
  }
})
</script> 